package com.luxuewen.sxa.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.luxuewen.sxa.entity.response.UserListRes;
import com.luxuewen.sxa.entity.response.UserRoleRes;
import com.luxuewen.sxa.common.enums.ResponseEnum;
import com.luxuewen.sxa.common.exception.ApiException;
import com.luxuewen.sxa.service.AuthService;
import com.luxuewen.sxa.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wen
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private SxaUsersServiceImpl sxaUsersService;



    public Map<String, Object> login(String username, String password) {
        // 获取登录的用户信息
        UserListRes userListRes = sxaUsersService.userInfo(username);
        if (userListRes == null) {
            throw new ApiException(ResponseEnum.FAILURE.getCode(), "未找到当前用户，请检查用户名！");
        }

        // 密码校验
        boolean res = BCrypt.checkpw(password, userListRes.getPassword());
        if (!res) {
            throw new ApiException(ResponseEnum.FAILURE.getCode(), "用户名或密码错误！");
        }

        // 生成token
        Map<String, Object> tokenInfo = new HashMap<>();
        tokenInfo.put("id", userListRes.getId());
        tokenInfo.put("name", userListRes.getName());
        tokenInfo.put("username", userListRes.getUsername());
        tokenInfo.put("departments", userListRes.getDepartments().stream().map(userDeptRes -> {
            Map<String, Object> dept = new HashMap<>();
            dept.put("id", userDeptRes.getId());
            dept.put("name", userDeptRes.getName());

            return dept;
        }).collect(Collectors.toList()));
        tokenInfo.put("roles", userListRes.getRoles().stream().map(userRoleRes -> {
            Map<String, Object> role = new HashMap<>();
            role.put("id", userRoleRes.getId());
            role.put("name", userRoleRes.getName());
            role.put("alias", userRoleRes.getAlias());

            return role;
        }).collect(Collectors.toList()));
        String token = JwtUtils.generateToken(tokenInfo);

        // 封装最后返回数据
        Map<String, Object> result = new HashMap<>();
        List<String> roleAliasList = userListRes.getRoles().stream().map(UserRoleRes::getAlias).collect(Collectors.toList());
        userListRes.setRole(roleAliasList);
        result.put("userInfo", userListRes);
        result.put("token", token);

        return result;
    }
}
